package org.amphiprion.montrictracv4.fragment;

import java.util.List;

import org.amphiprion.montrictracv4.App;
import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.adapter.GameListAdapter;
import org.amphiprion.montrictracv4.db.dao.GameDao;
import org.amphiprion.montrictracv4.db.model.Game;
import org.amphiprion.montrictracv4.db.model.GameExtensionList;
import org.amphiprion.montrictracv4.fragment.dialog.ExtensionListFragment;
import org.amphiprion.montrictracv4.task.ludotheque.SynchronizeExtensionOfGameTask;
import org.amphiprion.montrictracv4.task.ludotheque.SynchronizeGameTask;
import org.amphiprion.montrictracv4.task.ludotheque.SynchronizeGameTask.SynchronizeGameListener;
import org.amphiprion.montrictracv4.web.util.PreferenceUtil;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class GameListFragment extends SherlockFragment implements TricTracFragment {
	private View fragment;
	private LayoutInflater mInflater;
	private SherlockFragmentActivity context;
	private ListView listView;
	private View viewLoading;
	private EditText txtFilter;
	private ImageView btSort;

	private CheckBox chkExtension;
	private boolean showExtension;
	private GameListAdapter adapter;

	public GameListFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
		super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);

		this.context = getSherlockActivity();
		this.mInflater = paramLayoutInflater;
		this.fragment = paramLayoutInflater.inflate(R.layout.fragment_game_list, null);
		this.listView = ((ListView) this.fragment.findViewById(R.id.lstGame));
		this.viewLoading = this.fragment.findViewById(R.id.loading);

		this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View arg1, int row, long arg3) {
				// SynchronizeExtensionOfGameTask task = new SynchronizeExtensionOfGameTask(context, (Game) adapter.getItemAtPosition(row), new SynchronizeExtensionOfGameTask.SynchronizeExtensionOfGameListener() {
				//
				// @Override
				// public void importEnded(boolean succeed, GameExtensionList result) {
				// if (succeed) {
				// FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
				// ExtensionListFragment editNameDialog = ExtensionListFragment.newInstance(result);
				// editNameDialog.show(fm, "fragment_extension_list");
				// }
				// }
				// });
				// task.execute();

				try {
					Game game = (Game) adapter.getItemAtPosition(row);
					Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.trictrac.net/jeu-de-societe/" + game.getId() + "/infos"));
					startActivity(myIntent);
				} catch (ActivityNotFoundException e) {
					Toast.makeText(context, "No application can handle this request." + " Please install a webbrowser", Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		});

		listView.setVisibility(View.GONE);
		this.chkExtension = ((CheckBox) this.fragment.findViewById(R.id.chkShowAddons));

		ImageView btFilter = (ImageView) this.fragment.findViewById(R.id.btFilterList);
		btFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				txtFilter.setVisibility(View.VISIBLE);
				txtFilter.requestFocus();
				((InputMethodManager) getSherlockActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(txtFilter, InputMethodManager.SHOW_FORCED);
			}
		});
		txtFilter = (EditText) this.fragment.findViewById(R.id.txtFilterList);
		txtFilter.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				((InputMethodManager) getSherlockActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(txtFilter.getWindowToken(), 0);
				txtFilter.setVisibility(View.INVISIBLE);
				initData();
				return true;
			}
		});

		btSort = (ImageView) this.fragment.findViewById(R.id.btSort);
		btSort.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Editor editor = PreferenceUtil.pref.edit();
				editor.putBoolean("SORT_LUDO_GAME_BY_DATE", !PreferenceUtil.pref.getBoolean("SORT_LUDO_GAME_BY_DATE", false));
				editor.commit();
				initData();
			}
		});

		showExtension = chkExtension.isChecked();
		this.chkExtension.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				showExtension = chkExtension.isChecked();
				initData();
			}
		});
		return this.fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
	}

	public void initData() {
		updateSortIcon();

		if (App.currentLudotheque == null) {
			return;
		}

		viewLoading.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		new Thread(new Runnable() {

			@Override
			public void run() {
				List<Game> games = GameDao.getInstance(context).getGames(App.currentLudotheque.getId(), showExtension, txtFilter.getText().toString(), PreferenceUtil.pref.getBoolean("SORT_LUDO_GAME_BY_DATE", false));
				onLoadDone(games);
			}
		}).start();
	}

	private void updateSortIcon() {
		if (PreferenceUtil.pref.getBoolean("SORT_LUDO_GAME_BY_DATE", false)) {
			btSort.setImageResource(R.drawable.ic_order_alpha);
		} else {
			btSort.setImageResource(R.drawable.ic_order_date);
		}
	}

	private void onLoadDone(final List<Game> games) {
		listView.post(new Runnable() {

			@Override
			public void run() {
				if (App.currentSearch != null) {
					getActivity().setTitle(App.currentLudotheque.name + " (" + games.size() + " - " + App.currentSearch.name + ")");
				} else {
					getActivity().setTitle(App.currentLudotheque.name + " (" + games.size() + ")");
				}
				adapter = new GameListAdapter(context, GameListFragment.this, R.layout.game_list_item_row, games);
				listView.setAdapter(adapter);

				viewLoading.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
			}
		});
	}

	@Override
	public void menuOptionClicked(int id) {
		switch (id) {
		case R.id.action_add:
			// askMemberName();
			break;
		}
	}

	public void refreshGame(Game game) {
		SynchronizeGameTask task = new SynchronizeGameTask(context, new SynchronizeGameListener() {
			@Override
			public void importEnded(boolean succeed) {
				if (succeed) {
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
				}
			}
		});

		task.execute(game);

	}

	@Override
	public void refresh() {
		initData();
	}

	public void viewGameExtension(Game game) {
		SynchronizeExtensionOfGameTask task = new SynchronizeExtensionOfGameTask(context, game, new SynchronizeExtensionOfGameTask.SynchronizeExtensionOfGameListener() {

			@Override
			public void importEnded(boolean succeed, GameExtensionList result) {
				if (succeed) {
					FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
					ExtensionListFragment editNameDialog = ExtensionListFragment.newInstance(result);
					editNameDialog.show(fm, "fragment_extension_list");
				}
			}
		});
		task.execute();
	}
}
